#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <aio.h>

#define BUFSIZE 2048

void aio_completion_handler( sigval_t sigval)
{
	struct aiocb *req;

	req = (struct aiocb *)sigval.sival_ptr;

	/* Did the request complete? */
	if ((aio_error(req) == 0) && (aio_return(req) > 0) ) {
		printf("%s\n",(char *)req->aio_buf);
	}
}

int main(int argc, const char *argv[])
{
	int fd, ret;
	struct aiocb my_aiocb;

	fd = open( "file.txt", O_RDONLY);
	if (fd < 0)
		perror("open");
	
	/* Initialize the necessary fields in the aiocb */
	memset( (char *)&my_aiocb, 0, sizeof(struct aiocb) );
	my_aiocb.aio_fildes = fd;
	my_aiocb.aio_nbytes = BUFSIZE;
	my_aiocb.aio_offset = 0;
	my_aiocb.aio_buf = malloc(BUFSIZE+1);
	if ( !my_aiocb.aio_buf )
		perror("malloc");

	/* Link the AIO request with a thread callback */
	my_aiocb.aio_sigevent.sigev_notify = SIGEV_THREAD;
	my_aiocb.aio_sigevent.sigev_notify_function = aio_completion_handler;
	my_aiocb.aio_sigevent.sigev_notify_attributes = NULL;
	my_aiocb.aio_sigevent.sigev_value.sival_ptr = &my_aiocb;
	
	ret = aio_read( &my_aiocb );
	if (ret < 0)
		perror("aio_read");

	sleep(3);
	
	return 0;
}
